#!/usr/bin/env python

d='/data/audio'
l='00-Artists'

### CODE

import os, string, sys, pickle

# loading bestof history
try:
	history = pickle.load(open(d+'/.bestof_history','r'))
except:
	print 'Warning: '+d+'/.bestof_history doesn\'t exist. Creating an empty one.'
	try:
		f = open(d+'/.bestof_history','w')
		pickle.dump({}, f)
		f.close()
	except:
		print 'Can\'t create the bestof history file. Exiting.'
		sys.exit(0)
	history = pickle.load(open(d+'/.bestof_history','r'))

def my_deltree(file):
	for each in os.listdir(file):
		if os.lstat(file+'/'+each).st_mode & 0120000:
			os.unlink(file+'/'+each)
		elif os.lstat(file+'/'+each).st_mode & 0040000:
			my_deltree(file+'/'+each)
	os.rmdir(file)

# cleaning the symlinks tree
try:
	#os.removedirs(d+'/'+l)
	my_deltree(d+'/'+l)
except OSError, e:
	print str(e)
	sys.exit()

for year in os.listdir(d):
	try:
		int(year)
	except ValueError:
		continue
	for album in os.listdir(d+'/'+year):
		try:
			groupe = string.split(album, '-')[0]
		except IndexError:
			print 'Format error with: '+album
			continue
		try:
			os.makedirs(d+'/'+l+'/'+groupe)
		except OSError, e:
			if e.errno != 17:
				continue
		try:
			os.symlink('../../'+year+'/'+album, d+'/'+l+'/'+groupe+'/'+album)
		except OSError, e:
			if e.errno == 17:
				print 'Duplicate detected: '+album
		try:
			junk = history[album]
		except KeyError, e:
			print 'New album added to BEST_OF: '+album
			try:
				os.makedirs(d+'/BEST_OF/'+groupe)
			except OSError, e:
				if e.errno == 17: # already exists
					pass
			for filename in os.listdir(d+'/'+year+'/'+album):
				if filename[-4:] != '.ogg':
					continue
				#print 'splitting '+filename+' with '+groupe+'-'
				try:
					song = string.split(filename, groupe+'-')[1]
				except IndexError, e:
					print 'Unable to process file "'+filename+'"'
					sys.exit(0)
				#print d+'/'+year+'/'+album+'/'+filename+' -> '+d+'/BEST_OF/'+groupe+'/'+groupe+'-'+year+'-'+song
				try:
					os.link(d+'/'+year+'/'+album+'/'+filename, d+'/BEST_OF/'+groupe+'/'+groupe+'-'+year+'-'+song)
				except OSError, e:
					if e.errno == 17: # file exists
						pass
			history[album] = 1
			f = open(d+'/.bestof_history','w')
			pickle.dump(history, f)
			f.close()
